package logic

import (
	"context"
	"rent/models"

	"rent/rentrpc/internal/svc"
	"rent/rentrpc/rentrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommodityListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommodityListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommodityListLogic {
	return &CommodityListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommodityListLogic) CommodityList(in *rentrpc.CommodityListRequest) (*rentrpc.CommodityListResponse, error) {
	// todo: add your logic here and delete this line
	off := (in.Page - 1) * in.Size
	var commodity []models.CommodityData
	models.DB.Model(&models.Commodity{}).
		Select("commodities.*, users.user_name, users.image").
		Joins("LEFT JOIN users ON commodities.user_id = users.id").
		Offset(int(off)).Limit(int(in.Size)).
		Order("commoditys.created_at desc").
		Find(&commodity)
	var commodityDatas []*rentrpc.CommodityData
	for _, data := range commodity {
		commodityData := rentrpc.CommodityData{
			Title:     data.Title,
			Class:     data.Class,
			Price:     float32(data.Price),
			Details:   data.Details,
			UserName:  data.UserName,
			UserImage: data.Image,
		}
		commodityDatas = append(commodityDatas, &commodityData)
	}
	return &rentrpc.CommodityListResponse{
		List: commodityDatas,
	}, nil
}
